package com.jiajiakang;

import com.fasterxml.jackson.databind.JsonNode;
import com.jiajiakang.util.json.JsonUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class YuqueAPIClient {

    /** cookie */
    static String Cookie = "待替换";
    /** X-Csrf-Token */
    static String csrfToken = "待替换";


    public static void main(String[] args) {
        String baseUrL = "https://www.yuque.com/api";
        String personalBooksUrL = baseUrL + "/mine/personal_books";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // Step 1: 获取所有知识库的Id
            String personalBooksResponseString = get(httpClient, personalBooksUrL);
            JsonNode bookList = JsonUtil.findJsonNode(personalBooksResponseString, "data");
            // 1.1、遍历知识库
            for (JsonNode book : bookList) {
                String bookId = JsonUtil.findJsonNode2String(book, "id");
                String bookName = JsonUtil.findJsonNode2String(book, "name");

                // Step 2: 获取知识库下的所有文章
                String bookUrl = baseUrL + "/docs/?book_id=" + bookId;
                String docResponseString = get(httpClient, bookUrl);

                JsonNode docList = JsonUtil.findJsonNode(docResponseString, "data");
                // Step 3: 遍历知识库下的有所文章
                for (JsonNode doc : docList) {
                    String docId = JsonUtil.findJsonNode2String(doc, "id");

                    String exportURL = baseUrL + "/docs/" + docId + "/export";
                    Map<String, Object> jsonObject = new HashMap<>();
                    jsonObject.put("type", "markdown");
                    jsonObject.put("force", 0);
                    // jsonObject.put("options", "{\"latexType\": 2,\"enableAnchor\": 0,\"enableBreak\": 0}");
                    // latexType：1、导出 LaTeX 公式图片 2、导出 LaTeX 公式为 Markdown 语法
                    // enableAnchor：导出保持语雀的锚点              //  enableBreak：导出保持语雀的换行
                    jsonObject.put("options", "{\"latexType\":2}");
                    String exportResponseString = post(httpClient, exportURL, JsonUtil.toJson(jsonObject));
                    String downloadURL = JsonUtil.findJsonNode2String(exportResponseString, "data.url");
                    try {
                        // Step 3.1：保存文章到本地
                        saveFileFromURL(downloadURL, bookName);
                        break;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    private static String get(CloseableHttpClient httpClient, String url) throws IOException {
        HttpGet docRequest = new HttpGet(url);
        docRequest.setHeader("Cookie", Cookie);
        docRequest.setHeader("X-Csrf-Token", csrfToken);
        HttpResponse docResponse = httpClient.execute(docRequest);
        HttpEntity docEntity = docResponse.getEntity();
        return EntityUtils.toString(docEntity);
    }

    private static String post(CloseableHttpClient httpClient, String url, String body) throws IOException {
        HttpPost request = new HttpPost(url);
        request.setHeader("Cookie", Cookie);
        request.setHeader("X-Csrf-Token", csrfToken);
        request.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
        HttpResponse response = httpClient.execute(request);
        HttpEntity personalBooksEntity = response.getEntity();
        return EntityUtils.toString(personalBooksEntity);
    }

    public static void saveFileFromURL(String downloadUrl, String bookName) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(downloadUrl);
            httpGet.setHeader("Cookie", Cookie);
            httpGet.setHeader("X-Csrf-Token", csrfToken);

            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String fileName;
            if (response.getHeaders("Content-Disposition")[0].getElements()[0].getParameters().length == 2) {
                String file = response.getHeaders("Content-Disposition")[0].getElements()[0].getParameters()[1].getValue();
                fileName = URLDecoder.decode(file);
                fileName = fileName.substring(fileName.lastIndexOf("'") + 1);
            } else {
                fileName = response.getHeaders("Content-Disposition")[0].getElements()[0].getParameters()[0].getValue();
            }
            System.out.println("文件:" + fileName);
            File file = new File("C:\\Users\\User\\Desktop\\新建文件夹 (2)\\files\\" + bookName);
            if (!file.exists()) {
                file.mkdirs();
            }
            if (entity != null) {
                try (InputStream inputStream = entity.getContent();
                     FileOutputStream outputStream = new FileOutputStream("C:\\Users\\User\\Desktop\\新建文件夹 (2)\\files\\" + bookName + "/" + fileName)) {
                    byte[] buffer = new byte[1024];
                    int n;
                    while ((n = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, n);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}